package com.algorithm.learning.sort;

/**
 * @program: algorithm-learning
 * @description: 插入排序
 * @author: YuKai Fan
 * @create: 2024/8/17 23:04
 **/
public class InsertSort {

    public int[] sortArray(int[] nums) {
        // 循环变量，将nums[i]插入区间[0, i)使之成为有序数组
        for (int i = 1; i < nums.length; i++) {
            for (int j = i; j > 0 ; j--) {
                if (nums[j - 1] > nums[j]) {
                    swap(nums, j-1, j);
                } else {
                    break;
                }
            }
        }
        return nums;
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}
